import axios from 'axios'
import {
  getToken
} from '@/util/token'
import qs from 'qs'
import config from './config'
import router from './router'
import Vue from 'vue'
import {
  Toast
} from 'vant';
// 创建axios实例
const http = axios.create({
  baseURL: config.api_base,
  timeout: 15000,
  transformRequest: [
    function (data, headers) {
      data = data || {}
      data = qs.stringify(data)
      headers['token'] = getToken()
      return data
    }
  ]
})

// request拦截器
http.interceptors.request.use(config => {
  config.data = config.data ? config.data : {}
  if (router.currentRoute && router.currentRoute.meta.requiresAuth) {
    if (getToken() === '') {
      return Promise.reject('请登录后操作')
    } else {
      return config
    }
  } else {
    return config
  }
})

// respone拦截器
http.interceptors.response.use(
  response => {
    let data = response.data
    let msg = data.message || ''
    if (data.status_code >= 400) {
      if (data.status_code = 400) {
        if (response.config.url.split("?")[0].endsWith('bet/record')) {
          return data
        }
      }
      if (data.errors) {
        for (var obj in data.errors) {
          for (var i = 0; i < data.errors[obj].length; i++) {
            Toast(data.errors[obj][i]);
          }
        }
        return Promise.reject(new Error(msg))
      }
      // Vue.toasted.error(data.message, {
      //   icon: 'error'
      // }).goAway(2000)
      Toast(data.message)
      if (data.status_code == 403) {
        router.replace('/login')
      }
      return Promise.reject(new Error(msg))
    }
    return data
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

export default http
